<?php 

/*
* On va chercher les différents paramètres (venant de l'admin)
*/
if(get_option('wpspo_plugin_settings')) { extract(get_option('wpspo_plugin_settings')); }
$paramWpspoSetting = get_option('wpspo_plugin_settings');
if(get_option('wpspo_emails_settings')) { extract(get_option('wpspo_emails_settings')); }
$param_emailSettings = get_option('wpspo_emails_settings'); 


/*
 * Traitement si modification / validation de sa promesse
 */
if( !empty($_POST) && $_POST["postpromesse"]==true) {
    
    //*********** MODIFICATION ***************//
    if($_POST['modifier']==true && $_POST["idpromesse"]) {
        //Check si le titre n'est pas vide
        if(trim($_POST['valuepromesse']) == '') {
            $printError = __('Please indicate the amount of your pledge!', 'sponsorpress');
            $hasError = true;
        }
        // Si il n'y a pas d'erreur, on insère dans la table
        if(!isset($hasError)) {
            $updatePromesse = WPSPO_Promesse::updateMontantById($_POST["choixdefi"], $_POST["idpromesse"], $_POST["valuepromesse"], $_POST["valuetotal"]);
            unset($_POST);
            echo wpspo_redirection( 'admin.php?page=sponsor-dashboard&modifok=1' );
        }
    }
    
    //*********** SUPRESSION ***************//
    if($_POST['supprimer']==true && $_POST["idpromesse"]) {
        $deletePromesse = WPSPO_Promesse::delete($_POST["iduser"], $_POST["idpromesse"]);
        unset($_POST);
        echo wpspo_redirection( 'admin.php?page=sponsor-dashboard&deleteok=1' );
        exit();

    }
    
    //*********** VALIDATION ***************//
    if($_POST['valider']==true && $_POST["valide_idpromesse"]) {
        
        $validePromesse = WPSPO_Promesse::validate($_POST["valide_iduser"], $_POST["valide_idpromesse"]);
        $promesseDefi = get_post($_POST["valide_choixdefi"]);
        $user = get_userdata($_POST["valide_iduser"]);
        if($user_info->last_name!='' or $user_info->first_name!='') { $name_valide = $user_info->last_name.' '.$user_info->first_name; } else { $name_valide = $user->user_login; }
        
        $message_txt = $param_emailSettings['email_txt_validepromesse'];
        $message_html = $param_emailSettings['email_html_validepromesse'];
        $remplacements = array (
            "#_LOGIN" => $name_valide,
            "#_DEFI" => get_the_title($insertPost),
            "#_TOTAL_PROMESSSE" => $_POST["valide_validetotal"],
            "#_LINK_DEFI" => '<a href="'.get_permalink($_POST["valide_choixdefi"]).'" target="_blank">'.$promesseDefi->post_title.'</a>',
            "#_SITE" => esc_attr( get_bloginfo( 'name', 'display' ) ),
            "#_LINK_SITE" => esc_url( home_url( '/' ) )
        );
        $message_txt = str_replace(array_keys($remplacements), array_values($remplacements), $message_txt);
        $message_html = str_replace(array_keys($remplacements), array_values($remplacements), $message_html);
        $message_html = '<html><head></head><body>'.$message_html.'</body></html>';
        
        
        //=====Création de la boundary
        $boundary = "-----=".md5(rand());
        $emailTo = $user->user_email; 
        //$emailTo = "maillefaud.florent@gmail.com"; // pour les test
        if (!preg_match("#^[a-z0-9._-]+@(hotmail|live|msn).[a-z]{2,4}$#", $emailTo)) {
            $passage_ligne = "\r\n";
        } else {
            $passage_ligne = "\n";
        }       
        $subject = __( 'Notice of' , 'sponsorpress').' '.get_bloginfo('name');
        $headers[] = 'From: '.get_bloginfo('name').' <'.$emailTo.'>';
        $headers[] = 'Bcc: '.get_bloginfo('name').' <'.$paramWpspoSetting['emailplugin'].'>';
        $headers[] = "MIME-Version: 1.0".$passage_ligne;
        $headers[] = "Content-Type: multipart/alternative;".$passage_ligne." boundary=\"$boundary\"".$passage_ligne;

        //=====Création du message.
        $email_content = $passage_ligne."--".$boundary.$passage_ligne;
        //=====Ajout du message au format texte.
        $email_content.= "Content-Type: text/plain; charset=\"ISO-8859-1\"".$passage_ligne;
        $email_content.= "Content-Transfer-Encoding: 8bit".$passage_ligne;
        $email_content.= $passage_ligne.$message_txt.$passage_ligne;
        //==========
        $email_content.= $passage_ligne."--".$boundary.$passage_ligne;

        //=====Ajout du message au format HTML
        $email_content.= "Content-Type: text/html; charset=\"ISO-8859-1\"".$passage_ligne;
        $email_content.= "Content-Transfer-Encoding: 8bit".$passage_ligne;
        $email_content.= $passage_ligne.$message_html.$passage_ligne;
        //==========
        $email_content.= $passage_ligne."--".$boundary."--".$passage_ligne;
        $email_content.= $passage_ligne."--".$boundary."--".$passage_ligne;
        //==========
        
        if( wp_mail( $emailTo, $subject, $email_content, $headers ) ) {
             $emailSent = true;
        } else {
            exit('Erreur envoi mail');
        }
        unset($_POST);        
        echo wpspo_redirection( 'admin.php?page=sponsor-dashboard&validateok=1' );
        exit();
    }
    
}  else {
    
    $listeDefi = WPSPO_Defis::get_list();
    $listePromesses = WPSPO_Promesse::listByDefi($_POST["challenge_id"]);
    $listUsers = wpspo_list_users();
    /* Récupère la liste des projets */
    $listeProjet = WPSPO_Object::wpspo_getListProjets();
    
}
//print_r( $_POST );
?>
<style>
    .wpspo-confirm {
    color:#FFFFFF;
    border: 1px solid #008000;
    text-align: center;
    background-color:#008000;
    padding:3px;
    font-size: 1.075em;
    border-radius: 3px;
    margin-bottom: 15px;
}
.wpspo-erreur {
    color:#FFFFFF;
    border: 1px solid #990000;
    text-align: center;
    background-color:#990000;
    padding:3px;
    font-size: 1.075em;
    border-radius: 3px;
    margin-bottom: 15px;
}
</style>
<SCRIPT language="JavaScript1.2">
<!--
function Supprimer() {
    if( window.confirm("<?php _e('Are you sure you want to delete this promise? This deletion is final, you can not retrieve this promise.', 'sponsorpress'); ?>") ) {
        document.forms['delete_pledge'].submit();
        return true;
    }
}
function Valider() {
    if( window.confirm("<?php _e('Are you sure you want to validate this promise?', 'sponsorpress'); ?>") ) {
        document.forms['valide_pledge'].submit();
        return true;
    }
}
// -->
</SCRIPT>
<div class="wrap">
    <div id="icon-edit-comments" class="icon32"></div>
    <h2><?php _e('Pledges management', 'sponsorpress'); ?></h2>
    <div class="clear">&nbsp;</div>
    <form method="post" name="mod_filter" >
    <?php 
        if($listeProjet) {
            
            echo '<select name="project_id">';
            echo '<option value="#">--- '.__('Choose a Project', 'sponsorpress').' ---</option>';
            foreach($listeProjet as $lprojet) {
                echo '<option value="'.$lprojet->ID.'"';
                if($_POST["project_id"]==$lprojet->ID) { echo 'selected'; }
                echo '>'.$lprojet->post_title.'</option>';
            }
            echo '</select>';
        
            if($_POST["project_id"]) {
                $listeDefiByProject = WPSPO_Defis::listByProjet($_POST["project_id"]);
                if($listeDefiByProject) {
                    //print_r($listeDefiByProject);
                    echo '<select name="challenge_id">';
                    echo '<option value="#">--- '.__('Choose a Challenge', 'sponsorpress').' ---</option>';
                    foreach ( $listeDefiByProject as $leDefi ) {
                        echo '<option value="'.$leDefi->ID.'"';
                        if($_POST["challenge_id"]==$leDefi->ID) { echo 'selected'; }
                        echo '>'.$leDefi->post_title.'</option>';
                    } 
                    echo '</select>';
                } 
            }
        }
        ?>
        
        <input type="submit" value="Filtrer" />
    </form>
    <br /><br />
    <?php
        if($printError) { echo '<div class="wpspo-erreur">'.$printError.'</div>'; }
        if($_GET['modifok']) { echo '<div class="wpspo-confirm">'.__('This pledge has been modified', 'sponsorpress').'</div>'; }
        if($_GET['deleteok']) { echo '<div class="wpspo-erreur">'.__('This pledge has been deleted', 'sponsorpress').'</div>'; }
        if($_GET['validateok']) { echo '<div class="wpspo-confirm">'.__('This pledge has been validated', 'sponsorpress').'</div>'; }
    ?>
    <div style="float: left; width:100%;">
            <?php if($listePromesses) { ?>
                <table class="widefat">
                    <thead>
                        <tr>
                            <th><?php _e('User', 'sponsorpress'); ?></th>
                            <th><?php _e('Challenge', 'sponsorpress'); ?></th>
                            <th><?php _e('Pledge', 'sponsorpress'); ?></th>
                            <th><?php _e('Amounts', 'sponsorpress'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                       <?php
                            foreach ( $listePromesses as $promesse ) {
                                $userParticipant = get_userdata($promesse->promesse_id_user);
                                $first_name = $userParticipant-> user_firstname;
                                $last_name = $userParticipant-> user_lastname;
                                $nameParticipant = $first_name.' '.$last_name;
                                if($first_name=='' && $last_name=='') { $nameParticipant = ucfirst($userParticipant->user_login); }
                                $promesseDefi = get_post($promesse->promesse_id_defi);
                                $optionsDefi2 = WPSPO_Defis::get_optionsById($promesse->promesse_id_defi, $promesse->promesse_id_user);
                                $valueOptionsDefi = json_decode($optionsDefi2->defis_option_value);
                                if($valueOptionsDefi->mode_defis==1) { $addTexte = '/'.$valueOptionsDefi->text_mode_defis; }
                                
                                $msgDelete = __('Are you sure you want to delete this promise? This deletion is final, you can not retrieve this promise.', 'sponsorpress');
                       ?>
                       <tr>
                        <form method="post" name="mod_defi<?php echo $promesse->promesse_id; ?>" action="">
                            <td><?php echo $nameParticipant.'<br /><small>'.$userParticipant-> user_email.'</small>'; ?></td>
                            <td><a href="<?php echo get_permalink( $optionsDefi->defis_id_projet ); ?>"><?php echo $promesseDefi->post_title; ?></a></td>
                            <?php if($_GET['modif']==1 && $_GET['id']==$promesse->promesse_id_defi) { ?>
                                <td>
                                    <input type="text" name="valuepromesse" value="<?php echo $promesse->promesse_montant; ?>" style="width:80px;"><?php echo get_wpspo_currency_symbol().$addTexte; ?>
                                </td>
                                <td>
                                    <input type="text" name="valuetotal" value="<?php echo $promesse->promesse_total; ?>" style="width:80px;">
                                    <button><?php _e('Change', 'sponsorpress'); ?></button>
                                    <button type="button" onclick="location.href='admin.php?page=sponsor-dashboard'" ><?php _e('Cancel', 'sponsorpress'); ?></button>
                                    <input type="hidden" name="postpromesse" value="true">
                                    <input type="hidden" name="modifier" value="true">
                                    <input type="hidden" name="challenge_id" value="<?php echo $_POST["challenge_id"]; ?>">
                                 <input type="hidden" name="project_id" value="<?php echo $_POST["project_id"]; ?>">
                                    <input type="hidden" name="idpromesse" value="<?php echo $promesse->promesse_id; ?>">
                                    <input type="hidden" name="choixdefi" value="<?php echo $promesse->promesse_id_defi; ?>">
                                </td>                                
                            <?php } else { ?>
                                <td><?php echo wpspo_price($promesse->promesse_montant).$addTexte; ?></td>
                                <td><?php echo wpspo_price($promesse->promesse_total); ?></td>
                             <?php } ?>
                         </form>
                         <td>
                             <form name="valide_pledge" method="post">
                                 <input type="hidden" name="postpromesse" value="true">
                                 <input type="hidden" name="challenge_id" value="<?php echo $_POST["challenge_id"]; ?>">
                                 <input type="hidden" name="project_id" value="<?php echo $_POST["project_id"]; ?>">
                                 <input type="hidden" name="valide_iduser" value="<?php echo $promesse->promesse_id_user; ?>">
                                 <input type="hidden" name="valide_choixdefi" value="<?php echo $promesse->promesse_id_defi; ?>">
                                 <input type="hidden" name="valide_idpromesse" value="<?php echo $promesse->promesse_id; ?>">
                                 <input type="hidden" name="valide_validetotal" value="<?php echo $promesse->promesse_total.get_wpspo_currency_symbol(); ?>">
                                 <input type="hidden" name="valider" value="true">
                                 <a href="#" style="color: #fff;" onClick="return Valider();"><div style="background-color: #008000;color:#FFF;text-align: center;padding:3px;">Valider</div></a>
                             </form>
                         </td>
                         <td>
                             <a href="?page=sponsor-dashboard&amp;modif=1&amp;id=<?php echo $promesse->promesse_id_defi; ?>" style="color: #fff;"><div style="background-color: #F88C00;color:#FFF;text-align: center;padding:3px;">Modifier</div></a>
                         </td>
                         <td>
                             <form name="delete_pledge" method="post">
                                <input type="hidden" name="postpromesse" value="true">
                                <input type="hidden" name="iduser" value="<?php echo $promesse->promesse_id_user; ?>">
                                <input type="hidden" name="supprimer" value="true">
                                <input type="hidden" name="challenge_id" value="<?php echo $_POST["challenge_id"]; ?>">
                                 <input type="hidden" name="project_id" value="<?php echo $_POST["project_id"]; ?>">
                                <input type="hidden" name="idpromesse" value="<?php echo $promesse->promesse_id; ?>">
                                <a href="#" style="color: #fff;" onClick="return Supprimer();"  onfocus="this.blur()"><div style="background-color: #cd0a0a;color:#FFF;text-align: center;padding:3px;"><?php _e('Delete', 'sponsorpress'); ?></div></a>
                             </form>
                         </td>
                       </tr>
                       <?php } ?>
                    </tbody>
                </table>
            <?php } else { _e('Please, choose a project or challenge', 'sponsorpress');; } ?>
        </div>
    
    <div class="clear espace15">&nbsp;</div>
    <div>
        <div style="float: left; width:36%;margin-right: 1%;">
            <table class="wp-list-table widefat fixed" cellspacing="0">
                <thead>
                    <tr>
                        <th><?php _e('The latest participants', 'sponsorpress'); ?></th>
                    </tr>
                </thead>
                <tbody id="the-list">
                    <td>
                        <?php echo $listUsers; ?>
                    </td>
                </tbody>
            </table>
        </div>
        <div style="float: left; width:63%;">
            <?php if($listeDefi) { ?>
                <table class="widefat">
                    <thead>
                        <tr>
                            <th><?php _e('The latest challenges organized', 'sponsorpress'); ?></th>
                            <th><?php _e('Project', 'sponsorpress'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                       <?php
                            foreach ( $listeDefi as $defi ) {
                                $optionsListDefi = WPSPO_Defis::get_options($defi->ID);
                                $postListProjet = get_post($optionsListDefi->defis_id_projet);
                       ?>
                       <tr>
                         <td><a href="<?php echo get_permalink( $defi->ID ); ?>" target="_blank"><?php echo $defi->post_title; ?></a></td>
                         <td><a href="<?php echo get_permalink( $optionsListDefi->defis_id_projet ); ?>"><?php echo $postListProjet->post_title; ?></a></td>
                       </tr>
                       <?php } ?>
                    </tbody>
                </table>
            <?php } ?>
        </div>
    </div>
</div>
